package com.kgc.service.impl;

import com.github.pagehelper.PageInfo;
import com.kgc.dao.ProductEsDao;
import com.kgc.dao.ProductMapper;
import com.kgc.entity.Category;
import com.kgc.entity.Product;
import com.kgc.service.ProductService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author :qinya
 * @PackageName:com.kgc.service.impl
 * @ClassName: ProductServiceImpl
 * @Description: TODO
 * @date : 2025/5/16,21:35
 */
@Service
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductEsDao productEsDao;
    @Autowired
    private ElasticsearchRestTemplate ert;

    @Override
    public PageInfo<Product> selectByPage(Map<String, Object> params) {
        NativeSearchQueryBuilder nsqb = new NativeSearchQueryBuilder();
        if (params.containsKey("searchProductName")) {
            nsqb.withQuery(QueryBuilders.matchQuery("name", params.get("searchProductName")));
        } else {
            nsqb.withQuery(QueryBuilders.matchAllQuery());
        }
        // 添加分类 ID 搜索条件
        if (params.containsKey("searchCategoryId")) {
            Object searchCategoryId = params.get("searchCategoryId");
            System.out.println("searchCategoryId" + searchCategoryId);
            BoolQueryBuilder categoryQuery = QueryBuilders.boolQuery()
                    .should(QueryBuilders.termQuery("categoryLevel1Id", searchCategoryId))
                    .should(QueryBuilders.termQuery("categoryLevel2Id", searchCategoryId))
                    .should(QueryBuilders.termQuery("categoryLevel3Id", searchCategoryId));
            nsqb.withQuery(QueryBuilders.boolQuery().must(categoryQuery));
        }

        nsqb.withSort(SortBuilders.fieldSort("createDate").order(SortOrder.DESC));
        nsqb.withPageable(PageRequest.of((int) params.get("pageNum") - 1, (int) params.get("pageSize")));
        SearchHits<Product> searchHits = ert.search(nsqb.build(), Product.class);
        ArrayList<Product> list = new ArrayList<>();
        for (SearchHit<Product> searchHit : searchHits.getSearchHits()) {
            Product product = searchHit.getContent();
            list.add(product);
        }
        PageInfo<Product> pageInfo = new PageInfo<>();
        pageInfo.setList(list);
        pageInfo.setPageNum((int) params.get("pageNum"));
        pageInfo.setPageSize((int) params.get("pageSize"));
        pageInfo.setTotal(searchHits.getTotalHits());
        pageInfo.setPages((int) searchHits.getTotalHits() % pageInfo.getPageSize() > 0 ? (int) searchHits.getTotalHits() / pageInfo.getPageSize() + 1 : (int) searchHits.getTotalHits() / pageInfo.getPageSize());
        return pageInfo;
    }


    @Override
    public boolean editProduct(Product product) {
        boolean flag = productMapper.updateProduct(product) == 1;
        if (flag) {
            productEsDao.save(product);
        }
        return flag;
    }

    @Override
    public boolean addProduct(Product product) {
        boolean flag = productMapper.insertProduct(product) == 1;
        if (flag) {
            System.out.println("生成的自增主键为" + product.getId());
            productEsDao.save(product);
        }
        return flag;
    }

    @Override
    public boolean delProduct(String id) {
        boolean flag = productMapper.deleteProduct(id) == 1;
        if (flag) {
            productEsDao.deleteById(id);
        }
        return flag;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Product selectById(String id) {
        return productMapper.selectProductById(id);
    }

    @Override
    public boolean editProductStock(Product product) {
        return productMapper.updateProductStock(product) == 1;
    }

    @Override
    public List<Category> selectCategoryByProduct(Product product) {
        return productMapper.selectCategoryByProduct(product);
    }

    @Override
    public boolean checkStock(int preOut, String productId) {
        //返回true可预出库，false库存不足
        return selectById(productId).getStock() >= preOut;
    }
}
